package com.leeon.thread;

import static net.mindview.util.Print.print;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Car {
	private boolean waxOn = false;

	public synchronized void waxed() {
		waxOn = true;
		notifyAll();
	}

	public synchronized void buffed() {
		waxOn = false;
		notifyAll();
	}

	public synchronized void waitForWax() throws InterruptedException {
		while (waxOn == false) {
			wait();
		}
	}

	public synchronized void waitForBuffing() throws InterruptedException {
		while (waxOn == true) {
			wait();
		}
	}

}

class WaxOn implements Runnable {

	private Car mCar;

	public WaxOn(Car car) {
		this.mCar = car;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				print("wax on");
				TimeUnit.MICROSECONDS.sleep(200);
				mCar.waxed();
				mCar.waitForBuffing();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

}

class WaxOff implements Runnable{

	private Car mCar;
	
	public WaxOff(Car car) {
		this.mCar = car;
	}
	
	@Override
	public void run() {
		try {
			while(!Thread.interrupted()) {
				mCar.waitForWax();
				print("wax off");
				TimeUnit.MILLISECONDS.sleep(200);
				mCar.buffed();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

public class WaxOMatic {
	public static void main(String[] args) throws InterruptedException {
		Car car = new Car();
		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(new WaxOff(car));
		exec.execute(new WaxOn(car));
		TimeUnit.SECONDS.sleep(5);
		exec.shutdownNow();
	}
}
